package com.hxzy.projectssmplus.util;

import com.alibaba.fastjson.JSONObject;
import com.hxzy.projectssmplus.vo.AjaxResult;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class ServletUtil {

    /**
     * springmvc形式得到request
     * @return
     */
    public static HttpServletRequest  getReqeust(){
        //使用原始servlet来取
        RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes servletRequestAttributes= (ServletRequestAttributes) attributes;

        HttpServletRequest request = servletRequestAttributes.getRequest();
        return request;
    }

    /**
     * 向客户端输出消息
     * @param response
     * @param ajaxResult
     */
    public static void outJson(HttpServletResponse response, AjaxResult ajaxResult){
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        response.setStatus(200);
        try {
            PrintWriter out=response.getWriter();
            //java序列化成json
            String jsonStr= JSONObject.toJSONString(ajaxResult);
            out.print(jsonStr);
            out.flush();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
